package com.departmentstore.service.impl;

import com.departmentstore.entity.Manufacturer;
import com.departmentstore.repository.ManufacturerRepository;
import com.departmentstore.service.ManufacturerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class ManufacturerServiceImpl implements ManufacturerService {

    private final ManufacturerRepository manufacturerRepository;

    @Autowired
    public ManufacturerServiceImpl(ManufacturerRepository manufacturerRepository) {
        this.manufacturerRepository = manufacturerRepository;
    }

    @Override
    public Manufacturer createManufacturer(Manufacturer manufacturer) {
        return manufacturerRepository.save(manufacturer);
    }

    @Override
    public Manufacturer updateManufacturer(Manufacturer manufacturer) {
        if (!manufacturerRepository.existsById(manufacturer.getManufacturerId())) {
            throw new RuntimeException("制造商不存在");
        }
        return manufacturerRepository.save(manufacturer);
    }

    @Override
    public void deleteManufacturer(String manufacturerId) {
        if (!manufacturerRepository.existsById(manufacturerId)) {
            throw new RuntimeException("制造商不存在");
        }
        manufacturerRepository.deleteById(manufacturerId);
    }

    @Override
    @Transactional(readOnly = true)
    public Manufacturer getManufacturerById(String manufacturerId) {
        return manufacturerRepository.findById(manufacturerId)
                .orElseThrow(() -> new RuntimeException("制造商不存在"));
    }

    @Override
    @Transactional(readOnly = true)
    public List<Manufacturer> getAllManufacturers() {
        return manufacturerRepository.findAll();
    }

    @Override
    @Transactional(readOnly = true)
    public List<Manufacturer> getManufacturersByName(String name) {
        return manufacturerRepository.findByName(name);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Manufacturer> getManufacturersByAddress(String address) {
        return manufacturerRepository.findByAddress(address);
    }

} 